<template>
  <DataTable url="menu/list" ref="ds" :transform="tableTransform" @init="onDtInit">
    <template #tools="table">
      <div
          style="width: 90px;display: inline-block;line-height: 32px;height: 32px;vertical-align:bottom;padding-right:10px">
        <Select dict="UserType" v-model="table.params.menuGroup" :deletable="false" @change="table.reload()"/>
      </div>

      <Button v-if="ADD" icon="jeicon-add" color="primary" @click="add"><Lang zh="新增"/></Button>
      <Poptip v-if="EDIT" class="h-btn" :content="$t('确定重置内置菜单(不影响用户新增菜单)？','Are you sure to reset the built-in menu (without affecting the user\'s ability to add new menus)?')" @confirm="restMenu">
        <Button icon="icon-repeat" color="primary"><Lang zh="重置内置菜单" en="Reset Built-in Menus"/></Button>
      </Poptip>
    </template>
    <template #default="table">
      <Table :datas="table.data" ref="tb" :loading="table.loading">
        <TableItem :title="$t('图标')" :width="60" align="center">
          <template #default="{data}">
            <Tooltip
                theme="white"
                trigger="click"
                editable
            >
              <i :class="data.icon" class="pointer">{{ data.icon ? '' : '-' }}</i>
              <template #content>
                <div style="padding: 10px;">
                  <IconSelect v-model="data.icon" @update:modelValue="updateIcon(data,$event)"  style="width: 200px"/>
                </div>
              </template>
            </Tooltip>
          </template>
        </TableItem>
        <TableItem :title="$t('菜单','Menu')" prop="title" :format="decode" is-tree-opener>
        </TableItem>
        <TableItem :title="$t('类型','Type')" prop="menuType" :format="formatMenu" :width="120" align="center">
        </TableItem>
        <TableItem :title="$t('是否启用','Enable')" :width="80" align="center">
          <template #default="{data}">
            <Switch v-model="data.enable" @change="switchMenu(data)"/>
          </template>
        </TableItem>
        <TableItem :title="$t('内置菜单','Built-in')" align="center" :width="80">
          <template #default="{data}">
            <Checkbox :checked="data.system" />
          </template>
        </TableItem>
        <TableItem :title="$t('操作','Operation')" align="center" :width="180">
          <template #default="{data}">
            <LinkButtons>
              <Button @click="edit(data)"><Lang zh="详情"/></Button>
              <Button @click="doSort(data)"><Lang zh="排序" en="Order"/></Button>
              <Poptip :disabled="data.system" class="h-btn" content="确定删除该菜单及其子项？" @confirm="del(data)">
                <Button :disabled="data.system"><Lang zh="删除"/></Button>
              </Poptip>
            </LinkButtons>
          </template>
        </TableItem>
      </Table>
    </template>
  </DataTable>
  <Dialog href="platform/menuDialog.vue" ref="dlg" hasDivider hasCloseIcon>
    <template #header>系统菜单</template>
    <template #footer="dlg">
      <Button @click="dlg.cancel">取消</Button>
      <Button :loading="dlg.loading" color="primary" @click="dlg.submit">确认</Button>
    </template>
  </Dialog>
  <Modal v-model="showSort" hasDivider hasCloseIcon >
    <template #header>排序</template>
    <div class="h-table" style="width: 600px">
      <table class="h-table-header h-table-header-table" style="width:100%">
        <tr>
          <th class="h-table-th" width="20">图标</th>
          <th class="h-table-th text-left" width="40">菜单</th>
          <th class="h-table-th" width="20">是否启用</th>
          <th class="h-table-th" width="20">排序号</th>
        </tr>
      </table>
      <div class="h-table-container">
        <Draggable :list="sortList" tag="table" class="h-table-body-table" style="width: 100%;">
          <transition-group>
            <tr v-for="data in sortList" :key="data.id" style="cursor: move;" >
              <td width="20" class="text-center"><i :class="data.icon">{{ data.icon ? '' : '-' }}</i></td>
              <td width="40" class="text-left">{{data.title}}</td>
              <td width="20" class="text-center">{{data.enable}}</td>
              <td width="20" class="text-center">{{data.sort}}</td>
            </tr>
          </transition-group>
        </Draggable>
      </div>
    </div>
    <template #footer>
      <Button @click="showSort=false">取消</Button>
      <Button color="primary" @click="submitSort">确认</Button>
    </template>

  </Modal>
</template>
<script setup>
import {ajax, util, hasPermission, format} from 'framework'
import {ref, nextTick, onMounted, watch} from 'vue'
import {notice} from 'heyui'
import LinkButtons from "../coms/LinkButtons.vue";
import IconSelect from "./IconSelect.vue";
import {VueDraggableNext as Draggable} from 'vuedraggable'
import {decode,$t} from "i18n";
//权限
const ADD = hasPermission('platform.menu.add'), EDIT = hasPermission('platform.menu.edit'),
    DELETE = hasPermission('platform.menu.delete')

//数据集
const ds = ref({})
const showSearch = ref(false),showSort=ref(false);
const sortList=ref([])
//对话框的引用,可通过dlg.value.ref获取页面的引用
const dlg = ref({})
const tb = ref(null)

function onDtInit(table) {
  table.params.menuGroup = 'U'
}
function formatMenu(m){
  return m == 1 ? $t('权限','permission') : $t('菜单','menu')
}
function tableTransform(data) {
  //列表变为树
  let tree = util.asTree(data, it => it.id, it => it.parent)
  tree.sort((a, b) => a.sort - b.sort)
  setTimeout(() => tb.value.expandAll(), 10)
  return tree
}

//onMounted(()=>table.value.expandAll())
function search() {
  ds.value.reload()
}

async function add() {
  await dlg.value.open({menuGroup:ds.value.params.menuGroup})
  search()
}


async function edit(v) {
  if (!EDIT) {
    return;
  }
  await dlg.value.open(util.fields(v, 'id,menuGroup'))
  search()
}

async function del(it) {
  if (!DELETE) {
    return;
  }
  await ajax.post('menu/delete?menuGroup='+it.menuGroup+'&id='+it.id)
  search()
}
function updateIcon(data){
  ajax.post('menu/updateIcon', util.fields(data,"id,icon,menuGroup"))
      .then(r=>{
        notice("图标已修改")
      })
      .catch(e=>{
        notice("图标修改失败")
      })
}
function switchMenu(data){
  ajax.post('menu/switchMenu?id='+data.id+"&menuGroup="+data.menuGroup)
      .then(r=>{
        notice("菜单已切换")
      })
      .catch(e=>{
        notice("菜单切换失败")
      })
}
function findBrother(list,data){
  for(let it of list){
    if(it == data){
      return list
    }
  }
  for(let it of list){
    if(it.children){
      let brother=findBrother(it.children,data)
      if(brother!=null){
        return brother
      }
    }
  }
  return null
}

function doSort(data){
  let brother=findBrother(tb.value.datas,data)
  showSort.value=true
  sortList.value=brother.map(it=>util.fields(it,"id,icon,title,sort,enable"))
}
function submitSort(){
  let sorted=[]
  let i=1
  for(let item of sortList.value){
    sorted.push({id:item.id,menuGroup:ds.value.params.menuGroup,sort:i++})
  }
  ajax.post("menu/changeSort",sorted).then(r=>{
    showSort.value=false
    search()
  })
}
function restMenu(){
  ajax.post("menu/reset").then(r=>{
    search()
  })
}
</script>
